package com.cw.windows.action;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;

import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;

import com.cw.action.LotteryAction;
import com.cw.gui.MainPanel;

public class TileAction extends LotteryAction {

	public TileAction(String name, String icon, MainPanel t) {
		super(t, name, icon);
	}

	/**
	 * Invoked when an action occurs.
	 * 
	 * @param e
	 *            ActionEvent
	 * @todo Implement this java.awt.event.ActionListener method
	 */
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equalsIgnoreCase("WINDOWS_TILEH")) {
			tileH(mPanel.getDeskTop());
		} else {
			tileV(mPanel.getDeskTop());
		}
	}

	private void tileH(JDesktopPane desktopPane) {
		JInternalFrame[] frames = desktopPane.getAllFrames();
		if (frames.length == 0) {
			return;
		}

		tileH(frames, desktopPane.getBounds());
	}

	private void tileH(JInternalFrame[] frames, Rectangle dBounds) {
		int cols = (int) Math.round(Math.sqrt(frames.length));
		int rows = (int) (Math.ceil(((double) frames.length) / cols));
		int lastRow = frames.length - cols * (rows - 1);
		int width, height;

		if (lastRow == 0) {
			rows--;
			height = dBounds.height / rows;
		} else {
			height = dBounds.height / rows;
			if (lastRow < cols) {
				rows--;
				width = dBounds.width / lastRow;
				for (int i = 0; i < lastRow; i++) {
					frames[cols * rows + i].setBounds(i * width, rows * height,
							width, height);
				}
			}
		}
		width = dBounds.width / cols;
		for (int j = 0; j < rows; j++) {
			for (int i = 0; i < cols; i++) {
				frames[i + j * cols].setBounds(i * width, j * height, width,
						height);
			}
		}
	}

	private void tileV(JDesktopPane desktopPane) {
		JInternalFrame[] frames = desktopPane.getAllFrames();
		if (frames.length == 0) {
			return;
		}

		tileV(frames, desktopPane.getBounds());
	}

	private void tileV(JInternalFrame[] frames, Rectangle dBounds) {
		int rows = (int) Math.round(Math.sqrt(frames.length));
		int cols = (int) (Math.ceil(((double) frames.length) / rows));
		int lastcol = frames.length - rows * (cols - 1);
		int width, height;

		if (lastcol == 0) {
			cols--;
			width = dBounds.width / cols;
		} else {
			width = dBounds.width / cols;
			if (lastcol < rows) {
				cols--;
				height = dBounds.height / lastcol;
				for (int i = 0; i < lastcol; i++) {
					frames[cols * rows + i].setBounds(cols * width, i * height,
							width, height);
				}
			}
		}
		height = dBounds.height / rows;
		for (int j = 0; j < cols; j++) {
			for (int i = 0; i < rows; i++) {
				frames[i + j * rows].setBounds(j * width, i * height, width,
						height);
			}
		}
	}
}
